<template>
  <div class="content">
    <h3>place you want</h3>
    <el-tabs 
      v-model="tabsValue"
      type="card" 
      @tab-remove="removeTab"
      @tab-click="tabClick"
    >
      <el-tab-pane
        v-for="(item, index) in tabs"
        :key="item.name"
        :label="item.title"
        :name="item.name"
        :path="item.path"
        :closable="index !== 0"
      >
      </el-tab-pane>
    </el-tabs>
    <div class="router-box">
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
export default {
  name: 'tabs',
  data () {
    return {
      tabs: [
        {
          name: '首页',
          title: '首页',
          path: '/'
        },
        {
          name: '测试1',
          title: '测试1标题',
          path: '/test1'
        }
      ],
      tabsValue: '首页'
    }
  },
  mounted () {
    // 避免刷新或者浏览器地址栏直接输入未打开的tab页导致tab页标签与路由不匹配
    this.resetTab()
  },
  methods: {
    resetTab (newPath) {
      const path = newPath || this.$route.path
      let isExist = false
      this.tabs.forEach((item) => {
        if (item.path === path) {
          isExist = true
          this.tabsValue = item.name
        }
      })
      if (!isExist) {
        this.$router.replace(this.tabs[0].path)
      }
    },
    removeTab (tabName) {
      let tabs = this.tabs
      let activeName = this.tabsValue
      if (activeName === tabName) {
        tabs.forEach((tab, index) => {
          if (tab.name === tabName) {
            let nextTab = tabs[index + 1] || tabs[index - 1]
            if (nextTab) {
              activeName = nextTab.name
            }
          }
        })
        this.$router.go(-1)
      }

      this.tabs = tabs.filter(tab => tab.name !== tabName)
    },
    addTab (item) {
      let newTabName = item.name
      let isContain = false
      this.tabs.forEach((tab, index) => {
        if (tab.name === item.name) {
          isContain = true
        }
      }, this)

      if (!isContain) {
        this.tabs.push({
          title: newTabName,
          ...item
        })
      }

      this.tabsValue = newTabName
      this.$router.push(item.path)
    },
    tabClick (e) {
      // 避免路由重复添加
      if (e.$attrs.path === this.$route.path) {
        return
      }
      this.$router.push(e.$attrs.path)
    }
  },
  watch: {
    $route ({path}) {
      // 确保tab切换与router联动
      this.resetTab(path)
    }
  }
}
</script>

<style lang="scss">
  .content {
    margin: 0 0 0 220px;
    height: 100%;
    overflow: hidden;
    position: relative;
    h3 {
      margin: 20px;
    }
    .el-tabs__header {
      padding-left: 20px;
    }
    .router-box {
      position: absolute;
      top: 122px;
      bottom: 0;
      overflow: hidden;
      width: 100%;
      .box {
        padding: 20px;
        overflow-y: auto;
        height: 100%;
        width: 100%;
        box-sizing: border-box;
        p {
          height: 400px;
        }
      }
    }
  }
</style>

